import fs from "fs"
import path from "path"
import lodash from "lodash"
import YAML from "yaml"
import settings from "./lib/settings.js"

// 支持锅巴
export function supportGuoba() {
  return {
    // 插件信息，将会显示在前端页面
    pluginInfo: {
      name: "mirror-sync-plugin",
      title: "镜像同步插件",
      author: "Yunzai用户",
      authorLink: "",
      link: "",
      isV3: true,
      isV2: false,
      description: "Yunzai-Bot 镜像同步插件，支持一键同步插件到镜像站，支持多镜像自动故障转移",
      // 显示图标
      icon: "bx:sync",
      // 图标颜色
      iconColor: "#3b82f6",
    },
    // 配置项信息
    configInfo: {
      // 配置项 schemas
      schemas: [
        {
          component: "Divider",
          label: "GitHub 认证配置",
        },
        {
          field: "variables.GITHUB_USER",
          label: "GitHub 用户名",
          bottomHelpMessage: "用于访问 GitHub 私有仓库（源站或镜像站）",
          component: "Input",
          componentProps: {
            placeholder: "请输入 GitHub 用户名",
          },
        },
        {
          field: "variables.GITHUB_TOKEN",
          label: "GitHub Token",
          bottomHelpMessage: "GitHub Personal Access Token",
          component: "InputPassword",
          componentProps: {
            placeholder: "请输入 GitHub Token",
            autoComplete: "new-password",
          },
        },
        {
          component: "Divider",
          label: "GitCode 认证配置",
        },
        {
          field: "variables.GITCODE_USER",
          label: "GitCode 用户名",
          bottomHelpMessage: "用于访问 GitCode 私有仓库（源站或镜像站）",
          component: "Input",
          componentProps: {
            placeholder: "请输入 GitCode 用户名",
          },
        },
        {
          field: "variables.GITCODE_TOKEN",
          label: "GitCode Token",
          bottomHelpMessage: "GitCode Personal Access Token",
          component: "InputPassword",
          componentProps: {
            placeholder: "请输入 GitCode Token",
            autoComplete: "new-password",
          },
        },
        {
          component: "Divider",
          label: "CNB 认证配置",
        },
        {
          field: "variables.CNB_USER",
          label: "CNB 用户名",
          bottomHelpMessage: "用于访问 CNB 私有仓库（源站或镜像站）",
          component: "Input",
          componentProps: {
            placeholder: "请输入 CNB 用户名",
          },
        },
        {
          field: "variables.CNB_TOKEN",
          label: "CNB Token",
          bottomHelpMessage: "CNB Personal Access Token",
          component: "InputPassword",
          componentProps: {
            placeholder: "请输入 CNB Token",
            autoComplete: "new-password",
          },
        },
        {
          component: "Divider",
          label: "仓库映射配置",
        },
        {
          field: "enabled_repos",
          label: "镜像仓库映射",
          bottomHelpMessage: "配置需要同步的仓库映射关系",
          component: "GSubForm",
          componentProps: {
            multiple: true,
            schemas: [
              {
                field: "repo_name",
                label: "仓库名称",
                bottomHelpMessage: "用于标识仓库的名称",
                component: "Input",
                required: true,
                componentProps: {
                  placeholder: "例如：my-plugin",
                },
              },
              {
                field: "source_url",
                label: "源仓库地址",
                bottomHelpMessage: "原始仓库的 Git 地址",
                component: "Input",
                required: true,
                componentProps: {
                  placeholder: "例如：https://github.com/owner/repo",
                },
              },
              {
                field: "dest_urls",
                label: "镜像仓库地址列表",
                bottomHelpMessage: "镜像仓库的地址，按优先级排列",
                component: "GSubForm",
                componentProps: {
                  multiple: true,
                  schemas: [
                    {
                      field: "mirror_url",
                      label: "镜像地址",
                      component: "Input",
                      required: true,
                      componentProps: {
                        placeholder: "例如：https://gitcode.com/mirror/repo",
                      },
                    },
                  ],
                },
              },
            ],
          },
        },
      ],
      // 获取配置数据方法（用于前端填充显示数据）
      getConfigData() {
        try {
          // 通过 settings.js 读取配置（自动合并默认配置和用户配置）
          const config = settings.getConfig("token")
          if (!config) return {}

          const repos = Object.entries(config.enabled_repos || {}).map(([name, cfg]) => ({
            repo_name: name,
            source_url: cfg.source_url,
            dest_urls: (cfg.dest_urls || []).map(url => ({ mirror_url: url })),
          }))

          return {
            variables: config.variables || {},
            enabled_repos: repos,
          }
        } catch (error) {
          logger.error(`[镜像同步] 读取配置文件失败:`, error)
        }
        return {
          variables: {},
          enabled_repos: [],
        }
      },
      // 设置配置的方法（前端点确定后调用的方法）
      setConfigData(data, { Result }) {
        try {
          const configPath = path.join(
            process.cwd(),
            "plugins/mirror-sync-plugin/config/token.yaml",
          )

          // 读取现有用户配置
          let config = {}
          if (fs.existsSync(configPath)) {
            config = YAML.parse(fs.readFileSync(configPath, "utf8"))
          }

          // 更新配置（只更新用户修改的部分）
          if (data.variables) {
            config.variables = {
              ...config.variables,
              ...data.variables,
            }
          }

          if (data.enabled_repos) {
            logger.mark(
              "[镜像同步] 前端提交的仓库配置:",
              JSON.stringify(data.enabled_repos, null, 2),
            )
            const result = {}
            for (const repo of data.enabled_repos) {
              if (repo.repo_name && repo.source_url) {
                result[repo.repo_name] = {
                  source_url: repo.source_url,
                  dest_urls: (repo.dest_urls || [])
                    .filter(item => item.mirror_url)
                    .map(item => item.mirror_url),
                }
              }
            }
            config.enabled_repos = result
            logger.mark(
              "[镜像同步] 格式化后的仓库配置:",
              JSON.stringify(config.enabled_repos, null, 2),
            )
          }

          // 写入用户配置文件
          fs.writeFileSync(configPath, YAML.stringify(config), "utf8")

          logger.mark("[镜像同步] 用户配置文件已更新")

          return Result.ok({}, "保存成功~")
        } catch (error) {
          logger.error(`[镜像同步] 保存用户配置文件失败:`, error)
          return Result.error("保存失败：" + error.message)
        }
      },
    },
  }
}
